class Solution {
public:
    int maxFrequency(vector<int>& nums, int k, int numOperations) {
        int pos = 0,l = 0,r = 0,ans = 0,cnt = 1,n = nums.size();
        //
        sort(nums.begin(),nums.end());
        while(pos < n){

            if(pos < n - 1 && nums[pos] == nums[pos + 1]){
                cnt++;
                pos++;
                continue;
            }
            while(nums[pos] - nums[l] > k){
                l++;
            }
            while(r < n && nums[r] - nums[pos] <= k){
                r++;
            }
            ans = max(ans,min(r - l,numOperations + cnt));
            pos++;
            // cout << l << ' ' << r << endl;
            cnt = 1;
        }
        if(ans >= numOperations){
            return ans;
        }

        l = 0,r = 0;
        while(r < n){
            while(nums[r] - nums[l] > 2 * k){
                l++;
            }
            r++;
            ans = max(ans,min(r - l,numOperations));
        }
        return ans;
    }
};